//
//  UserAccountModel.swift
//  01_新浪微博
//
//  Created by 黄蓉 on 15/12/16.
//  Copyright © 2015年 黄蓉. All rights reserved.
//

import UIKit
import AFNetworking
class UserAccountModel: NSObject {
    
    var account : UserAccount?
    
    override init() {
        
        account = UserAccount.loadAccount()
        super.init()
    }
    
    
    var userLogin: Bool {
        return account?.access_token == nil
    }
    
    var headUrl: NSURL? {
        let url = NSURL(string: account?.avatar_large ?? "")
        return url
    }
    
    var uerName : String? {
        return account?.name
    }
    
    
    
    
    
    
    
    ///  根据授权码获取令牌
    func loadAccessToken(code: String,finish: (isSuccess: Bool) -> ()) {
        //拼接url
        //https://api.weibo.com/oauth2/access_token
        let urlString = "oauth2/access_token"
        
        // 2. 请求参数
        let params = ["client_id": WB_Client,
            "client_secret": WB_AppSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WB_Redirect_URI]
        
        
        NetWorkingTools.shareNetWorkingTools().POST(urlString, parameters: params, progress: { (_) -> Void in
            
            }, success: { (_, json) -> Void in
                
                if let account = json {
                    
                    self.loadUserInfo(account as! UserAccount, finish: finish)
                }
                
            }) { (_, error) -> Void in
                print(error.description)
        }
    }
    //获取用户信息
    func loadUserInfo(account: UserAccount,finish: (isSuccess: Bool) -> ()) {
        if let access_token = account.access_token, let uid = account.uid{
            
            let params = ["access_token" : access_token ,"uid" :uid]
            NetWorkingTools.shareNetWorkingTools().GET("2/users/show.json", parameters: params, progress: { (_) -> Void in
                
                }, success: { (_, JSON) -> Void in
                    //                print(JSON)
                    
                    if  let dict = JSON {
                        account.name = dict["name"] as? String
                        account.avatar_large = dict as? String
                        account.saveAccount()
                        finish(isSuccess: true)
                    }
                    
                    
                }) { (_, error) -> Void in
                    //                print(error.description)
                    finish(isSuccess: false)
            }
            
            
        }
    }

    
}
